document.addEventListener('DOMContentLoaded', function() {
    // WebSocket 连接相关变量
    let socket = null;
    const connectBtn = document.getElementById('connectBtn');
    const disconnectBtn = document.getElementById('disconnectBtn');
    const clearBtn = document.getElementById('clearBtn');
    const statusSpan = document.getElementById('status');
    
    // 日志数据存储
    let allLogs = [];
    let filteredLogs = [];
    const logsPerPage = 50;
    let currentPage = 1;
    
    // 过滤元素
    const ipFilter = document.getElementById('ipFilter');
    const methodFilter = document.getElementById('methodFilter');
    const uriFilter = document.getElementById('uriFilter');
    const resultFilter = document.getElementById('resultFilter');
    const portFilter = document.getElementById('portFilter');
    
    // 分页元素
    const prevPageBtn = document.getElementById('prevPage');
    const nextPageBtn = document.getElementById('nextPage');
    const pageInfoSpan = document.getElementById('pageInfo');
    
    // 连接WebSocket服务器
    function connectWebSocket() {
        // 根据你的实际部署情况修改WebSocket URL
        const wsUrl = `ws://${window.location.hostname}:8080/ws`;
        socket = new WebSocket(wsUrl);
        
        socket.onopen = function() {
            statusSpan.textContent = '已连接';
            statusSpan.className = 'status connected';
            connectBtn.disabled = true;
            disconnectBtn.disabled = false;
            console.log('WebSocket连接已建立');
        };
        
        socket.onclose = function() {
            statusSpan.textContent = '未连接';
            statusSpan.className = 'status disconnected';
            connectBtn.disabled = false;
            disconnectBtn.disabled = true;
            console.log('WebSocket连接已关闭');
        };
        
        socket.onerror = function(error) {
            console.error('WebSocket错误:', error);
            statusSpan.textContent = '连接错误';
            statusSpan.className = 'status disconnected';
        };
        
        socket.onmessage = function(event) {
            try {
                const logMessage = JSON.parse(event.data);
                console.log('收到日志:', logMessage);
                
                // 添加到日志数组开头（最新日志显示在最上面）
                allLogs.unshift(logMessage);
                
                // 应用过滤并刷新显示
                applyFilters();
            } catch (e) {
                console.error('解析日志消息失败:', e);
            }
        };
    }
    
    // 断开WebSocket连接
    function disconnectWebSocket() {
        if (socket) {
            socket.close();
            socket = null;
        }
    }
    
    // 清空日志
    function clearLogs() {
        allLogs = [];
        filteredLogs = [];
        currentPage = 1;
        renderLogs();
        updatePagination();
    }
    
    // 应用过滤条件
    function applyFilters() {
        const ipFilterValue = ipFilter.value.toLowerCase();
        const methodFilterValue = methodFilter.value.toUpperCase();
        const uriFilterValue = uriFilter.value.toLowerCase();
        const resultFilterValue = resultFilter.value;
        const portFilterValue = portFilter.value;
        
        filteredLogs = allLogs.filter(log => {
            return (ipFilterValue === '' || log.client_ip.toLowerCase().includes(ipFilterValue)) &&
                   (methodFilterValue === '' || log.method.toUpperCase().includes(methodFilterValue)) &&
                   (uriFilterValue === '' || log.uri.toLowerCase().includes(uriFilterValue)) &&
                   (resultFilterValue === '' || log.result === resultFilterValue) &&
                   (portFilterValue === '' || String(log.port).includes(portFilterValue));
        });
        
        currentPage = 1;
        renderLogs();
        updatePagination();
    }
    
    // 渲染日志到表格
    function renderLogs() {
        const logBody = document.getElementById('logBody');
        logBody.innerHTML = '';
        
        const startIdx = (currentPage - 1) * logsPerPage;
        const endIdx = Math.min(startIdx + logsPerPage, filteredLogs.length);
        const logsToShow = filteredLogs.slice(startIdx, endIdx);
        
        if (logsToShow.length === 0) {
            const row = document.createElement('tr');
            row.innerHTML = '<td colspan="6" style="text-align: center;">没有日志数据</td>';
            logBody.appendChild(row);
            return;
        }
        
        logsToShow.forEach(log => {
            const row = document.createElement('tr');
            
            // 根据结果设置行样式类
            let resultClass = '';
            if (log.result === 'ALLOW') {
                resultClass = 'success';
            } else if (log.result === 'BLOCK') {
                resultClass = 'danger';
            }
            
            row.innerHTML = `
                <td>${log.timestamp}</td>
                <td>${log.client_ip}</td>
                <td>${log.method}</td>
                <td>${log.uri}</td>
                <td>${log.port}</td>
                <td class="${resultClass}">${log.result}</td>
            `;
            
            logBody.appendChild(row);
        });
    }
    
    // 更新分页控件状态
    function updatePagination() {
        const totalPages = Math.ceil(filteredLogs.length / logsPerPage);
        
        pageInfoSpan.textContent = `第 ${currentPage} 页 / 共 ${totalPages} 页`;
        
        prevPageBtn.disabled = currentPage <= 1;
        nextPageBtn.disabled = currentPage >= totalPages || totalPages === 0;
    }
    
    // 事件监听器
    connectBtn.addEventListener('click', connectWebSocket);
    disconnectBtn.addEventListener('click', disconnectWebSocket);
    clearBtn.addEventListener('click', clearLogs);
    
    // 过滤控件事件
    ipFilter.addEventListener('input', applyFilters);
    methodFilter.addEventListener('input', applyFilters);
    uriFilter.addEventListener('input', applyFilters);
    resultFilter.addEventListener('change', applyFilters);
    portFilter.addEventListener('input', applyFilters);
    
    // 分页控件事件
    prevPageBtn.addEventListener('click', () => {
        if (currentPage > 1) {
            currentPage--;
            renderLogs();
            updatePagination();
        }
    });
    
    nextPageBtn.addEventListener('click', () => {
        const totalPages = Math.ceil(filteredLogs.length / logsPerPage);
        if (currentPage < totalPages) {
            currentPage++;
            renderLogs();
            updatePagination();
        }
    });
    
    // 初始状态
    applyFilters();
});